import PureMachineSourceManage from '../components/machine-source-manage';
import * as MachineAction from 'actions/machine';
import { getFetchStatus } from 'actions/util';
import * as React from 'react';
import * as ReactRedux from 'react-redux';

const mapStateToProps = state => {
  return {
    isFetching: getFetchStatus(state, MachineAction.listMachineSourcesByCompanyId),
    sources: state.companymMachineSourceList
  };
};

const mapDispatchToProps = dispatch => {
  const props = {
    initFetch(companyId) {
      dispatch(MachineAction.listMachineSourcesByCompanyId(companyId));
    },
    onLockSource(source) {
      return dispatch(MachineAction.lockMachineSource(source))
        .then(() => dispatch(MachineAction.listAllMachineSources()));
    },
    onUnlockSource(source) {
      return dispatch(MachineAction.unlockMachineSource(source))
        .then(() => dispatch(MachineAction.listAllMachineSources()));
    },
    onMachineSourceInsert(source, companyId) {
      return dispatch(MachineAction.createCompanyMachineSource(companyId, source))
        .then(() => dispatch(MachineAction.listMachineSourcesByCompanyId(companyId)));
    },
    onMachineSourceUpdate(source, companyId) {
      return dispatch(MachineAction.updateCompanyMachineSource(companyId, source))
        .then(() => dispatch(MachineAction.listMachineSourcesByCompanyId(companyId)));
    }
  };
  return props;
};

class MachineSourceManageCompany extends React.Component {
  componentDidMount() {
    this.props.initFetch(this.props.companyId);
  }

  render() {
    return <PureMachineSourceManage {...this.props}/>;
  }
}

export default ReactRedux.connect(mapStateToProps, mapDispatchToProps)(MachineSourceManageCompany);
